package com.fg.cloud.manager.service.order.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fg.cloud.common.NumberUtil;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.finals.AgencyBill;
import com.fg.cloud.common.finals.LogContent;
import com.fg.cloud.common.finals.LogStatus;
import com.fg.cloud.common.finals.OrderStatus;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.manager.entry.agency.AgencyBillEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.entry.order.OrderReturnDetailEntity;
import com.fg.cloud.manager.entry.order.OrderReturnEntity;
import com.fg.cloud.manager.entry.order.OrderReturnLogEntity;
import com.fg.cloud.manager.entry.order.vo.OrderReturnDetailVo;
import com.fg.cloud.manager.entry.order.vo.OrderReturnVo;
import com.fg.cloud.manager.mapper.agency.AgencyBillMapper;
import com.fg.cloud.manager.mapper.order.OrderRefundDetailMapper;
import com.fg.cloud.manager.mapper.order.OrderRefundMapper;
import com.fg.cloud.manager.mapper.order.OrderReturnFileMapper;
import com.fg.cloud.manager.mapper.order.OrderReturnLogMapper;
import com.fg.cloud.manager.service.order.OrderRefundsService;

@Service
public class OrderRefundsServiceImpl implements OrderRefundsService{

	@Autowired
	private OrderRefundMapper refundMapper;
	
	@Autowired
	private OrderRefundDetailMapper refund_detailMapper;
	
	@Autowired
	private OrderReturnLogMapper return_logMapper;
	
	@Autowired
	private OrderReturnFileMapper return_fileMapper;
	
	@Autowired
	private AgencyBillMapper return_billMapper;
	
	/**
	 * 删除退货单相关记录（详情、日志、附件）
	 */
	@Override
	@Transactional
	public boolean deleteRefunds(Long facId) {
		//1.删除退货单详情
		long r1 = refund_detailMapper.delByfacId(facId);
		if ( r1 <= 0 ) return false;
		//2.删除退货单日志
		long r2 = return_logMapper.delByfacId(facId);
		if ( r2 <= 0 ) return false;
		//3.删除退货单附件
		long r3 = return_fileMapper.delByfacId(facId);
		if ( r3 <= 0 ) return false;
		//4.删除退货单
		long r4 = refundMapper.delByfacId(facId);
		
		if ( r1 > 0 && r2 > 0 && r3 > 0 && r4 > 0 ) {
			return true;
		}
		return false;
	}
	
	/**
	 * 批量删除
	 */
	@Override
	@Transactional
	public boolean deletes(Long[] ids, Long facId, Long ageId) {
		//删除日志
		return_logMapper.deletes(ids);
		//删除附件
		return_fileMapper.deletes(ids);
		//删除退货详情
		refund_detailMapper.deleteByOrderReturnIds(ids);
		//删除退货单头
		return refundMapper.deletes(ids, facId, ageId) > 0 ? true : false;
	}
	
	/**
	 * Description:封装退货单操作日志
	 * @param returnId 退货单ID
	 * @param content 日志内容
	 * @param type 类型
	 * @return
	 * @author around
	 * @date 2017年9月5日下午3:13:04
	 */
	private OrderReturnLogEntity getOrderReturnLogEntity(Long returnId,
			String content, Integer type) {
		OrderReturnLogEntity entity = new OrderReturnLogEntity();
		//判别处理用户类型
		if (UserUtils.getCurrentUser() instanceof FactoryUserVo) {
			FactoryUserVo user = (FactoryUserVo) UserUtils.getCurrentUser();
			entity.setCompanyId(user.getFacId());
			entity.setCompanyName(user.getFacName());
			entity.setOperatorId(user.getId());
			entity.setOperatorName(user.getTrueName());
		} else if (UserUtils.getCurrentUser() instanceof AgencyUserVo) {
			AgencyUserVo user = (AgencyUserVo) UserUtils.getCurrentUser();
			entity.setCompanyId(user.getAgeId());
			entity.setCompanyName(user.getAgencyName());
			entity.setOperatorId(user.getId());
			entity.setOperatorName(user.getTrueName());
		}
		entity.setReturnId(returnId);
		entity.setOperatorTime(new Date());
		entity.setContent(content);
		entity.setType(type);
		return entity;
	}

	/**
	 * 退货单新增
	 */
	@Override
	@Transactional
	public boolean insert(OrderReturnVo entity) {
		//计算总额 = 子项目总金额的和
		List<OrderReturnDetailEntity> oelist = entity.getDetailList();
		BigDecimal amountSum = BigDecimal.valueOf(0);// 总金额
		for (int i = 0; i<oelist.size();i++){
			//总金额 = 本次发货数量*单位换算数量*单价
			amountSum = amountSum.add(oelist.get(i).getAmount().
					multiply(BigDecimal.valueOf(oelist.get(i).getUnitNum())).
					multiply(oelist.get(i).getPrice()));
		}
		entity.setAmountTotal(amountSum);
		//编码规则
		entity.setReturnNo(NumberUtil.getOrderNumber());
		//新增退货单,成功后获取插入的退货单id  赋值给子节点
		int count = refundMapper.insertSelective(entity);
		//新增退货单详情
		OrderReturnDetailEntity detail = null;
		for (int i= 0; i < oelist.size(); i++){
			detail = oelist.get(i);
			detail.setReturnId(entity.getId());
			detail.setReturnNo(entity.getReturnNo());
			refund_detailMapper.insertSelective(detail);
		}
		//新增附件列表
		List<String> fileList = entity.getFileList();
		if (fileList != null && fileList.size() > 0){
			return_fileMapper.batchInsert(fileList, entity.getId());
		}
		//插入日志
		return_logMapper.insert(getOrderReturnLogEntity(entity.getId(), 
				LogContent.RETURN_ADD, LogStatus.RETURN_ADD));
		return count > 0 ? true : false;
	}

	/**
	 * 列表查询
	 */
	@Override
	public void findList(PageUtils<OrderReturnEntity> pageinfo) {
		long cont = refundMapper.findCount(pageinfo);
		pageinfo.setTotal(cont);
		if(cont > 0){
			pageinfo.setData(refundMapper.findList(pageinfo));
		}else{
			pageinfo.setData(new ArrayList<OrderReturnEntity>());
		}
	}

	/**
	 * 查询退货单
	 */
	@Override
	public OrderReturnVo find(Long id, Long facId, Long ageId) {
		OrderReturnVo entity = refundMapper.find(id, facId, ageId);
		if (null == entity) return null;
		//退货单详情
		entity.setDetailList(refund_detailMapper.findByOrderReturnId(entity.getId()));
		//退货单附件
		entity.setFileList(return_fileMapper.findList(entity.getId()));
		//退货单日志
		entity.setLogList(return_logMapper.findList(entity.getId()));
		return entity;
	}

	/**
	 * 动态修改
	 */
	@Override
	@Transactional
	public boolean update(OrderReturnVo entity) {
		if (entity.getStatus() > 1) return false;
		//保存当前的
		List<OrderReturnDetailEntity> detailList = entity.getDetailList();
		for (OrderReturnDetailEntity orderReturnDetailEntity : detailList) {
			refund_detailMapper.updateByPrimaryKeySelective(orderReturnDetailEntity);
		}
		//删除前端去掉的退货单详情数据
		if (StringUtils.isNotEmpty(entity.getRemoveDetailIds()) 
				&& entity.getRemoveDetailIds().length() > 0) {
			String removeIds = entity.getRemoveDetailIds().replaceAll("\\[]", "");
			refund_detailMapper.deletes(LongUtils.convert(
					removeIds.split("[, ]+")));
		}
			
		//更新退货单对应的附件
		return_fileMapper.delete(entity.getId());
		if (entity.getFileList().size() > 0)
			return_fileMapper.batchInsert(entity.getFileList(), entity.getId());
		
		//添加日志
		return_logMapper.insert(getOrderReturnLogEntity(entity.getId(), 
				LogContent.RETURN_UPDATE, LogStatus.RETURN_SUBMIT));
		
		return refundMapper.updateByPrimaryKeySelective(entity) > 0 ? true : false;
	}

	

	/**
	 * 提交（待审核）
	 */
	@Override
	@Transactional
	public boolean confirm(OrderReturnEntity entity) {
		//变更状态
		entity.setStatus(OrderStatus.RETURN_AUDIT);
		//记录日志
		return_logMapper.insert(getOrderReturnLogEntity(entity.getId(), 
				LogContent.RETURN_SUBMIT, LogStatus.RETURN_SUBMIT));
		return refundMapper.updateByPrimaryKeySelective(entity) > 0 ? true : false;
	}

	/**
	 * 审核（待退货）
	 */
	@Override
	@Transactional
	public boolean audit(OrderReturnEntity entity) {
		//变更状态
		entity.setStatus(OrderStatus.RETURN_DELIVE);
		//记录日志
		return_logMapper.insert(getOrderReturnLogEntity(entity.getId(), 
				LogContent.RETURN_AUDIT, LogStatus.RETURN_AUDIT));
		return refundMapper.updateByPrimaryKeySelective(entity) > 0 ? true : false;
	}

	/**
	 * 退货（待收货）
	 */
	@Override
	@Transactional
	public boolean delive(OrderReturnEntity entity) {
		//变更状态
		entity.setStatus(OrderStatus.RETURN_DELIVERY);
		//记录日志
		return_logMapper.insert(getOrderReturnLogEntity(entity.getId(), 
				LogContent.RETURN_DELIVE, LogStatus.RETURN_DELIVE));
		return refundMapper.updateByPrimaryKeySelective(entity) > 0 ? true : false;
	}

	/**
	 * 收货（待退款）
	 */
	@Override
	@Transactional
	public boolean delivery(OrderReturnEntity entity) {
		//变更状态
		entity.setStatus(OrderStatus.RETURN_REFUND);
		//记录日志
		return_logMapper.insert(getOrderReturnLogEntity(entity.getId(), 
				LogContent.RETURN_DELIVERY, LogStatus.RETURN_DELIVERY));
		return refundMapper.updateByPrimaryKeySelective(entity) > 0 ? true : false;
	}

	/**
	 * 退款（完成）
	 */
	/* (non-Javadoc)
	 * @see com.fg.cloud.manager.service.order.OrderRefundsService#refund(com.fg.cloud.manager.entry.order.OrderReturnEntity)
	 */
	@Override
	@Transactional
	public boolean refund(OrderReturnEntity entity) {
		//变更状态
		entity.setStatus(OrderStatus.RETURN_SUCCESS);
		//记录日志
		return_logMapper.insert(getOrderReturnLogEntity(entity.getId(), 
				LogContent.RETURN_REFUND, LogStatus.RETURN_REFUND));
		//插入退款流水记录
		FactoryUserVo user = (FactoryUserVo) UserUtils.getCurrentUser();
		AgencyBillEntity bill = new AgencyBillEntity();
		bill.setFacId(entity.getFacId());
		bill.setAgeId(entity.getAgeId());
		bill.setRunningNum(NumberUtil.getSerialNumber());
		bill.setAmount(entity.getAmountPay());
		bill.setTransInfo(AgencyBill.REFUND);
		bill.setTransMode(AgencyBill.REFUND_MODE);
		//bill.setPayAccount(1);
		bill.setTransTime(new Date());
		bill.setStatus(1);
		bill.setConfirmAmount(entity.getNeedPay());
		bill.setConfirmTime(new Date());
		bill.setOrderId(entity.getId());
		bill.setAdmin(user.getTrueName());
		bill.setOrderNum(entity.getReturnNo());
		//bill.setRemark("退货单:"+entity.getReturnNo()+"退款");
		return_billMapper.insert(bill);
		
		return refundMapper.updateByPrimaryKeySelective(entity) > 0 ? true : false;
	}

	@Override
	public List<OrderReturnDetailVo> findByOrderId(Long[] ids) {
		List<OrderReturnDetailVo> list = refund_detailMapper.findByOrderId(ids);
		for (OrderReturnDetailVo entity : list) {
			if (StringUtils.isNotEmpty(entity.getProductSpec()))
				/*entity.setProductSpec("【".concat(
						entity.getProductSpec().replaceAll("[{}\" ]+", "")).concat("】"));*/
				entity.setProductSpec(entity.getProductSpec().replace("{", "【").replace("}", "】"));
		}
		return list;
	}
	

	public static void main(String[] args) {
		String removeIds = "[]".replaceAll("\\[]", "");
		System.out.println(removeIds.length());
	}

	
	
}
